<template>
  <div class="template-list">
    <div>
      <Button type="primary" @click="addTemplate()">新增模板</Button>
    </div>
    <div>
      <Table class="template-content" :columns="columns" :data="templateData">
        <template slot-scope="{ row }" slot="action">
          <div class="table-form-action-box">
            <span
              class="table-blue action-btn"
              style="margin-right: 10px;"
              @click="toEditOrDel(row,1)"
            >编辑</span>
            <span class="table-red" @click="toEditOrDel(row,0)">删除</span>
          </div>
        </template>
      </Table>
      <Page
        style="margin-bottom: 10px;"
        v-show="pagination.total > pagination.pageSize || pagination.pageSize > 10"
        @on-change="changePageNum"
        @on-page-size-change="changePageSize"
        :total="pagination.total"
        :current="pagination.current"
        :page-size="pagination.pageSize"
        :transfer="true"
        show-sizer
        show-total
      />
    </div>

    <!-- 版本选择提示 -->
    <Modal :width="400" v-model="versionShow" footer-hide class="version-show-model">
      <div class="version-show-item">
        <span>
          请选择
          <span :class="['version-bold',{'del':actionName==='删除'}]">{{actionName}}</span> 的版本号：
        </span>
        <Select v-model="version" clearable>
          <Option
            v-for="item of versionObj[actionId]"
            :key="item.version"
            :value="item.version"
          >v{{item.version}}</Option>
        </Select>
      </div>

      <div class="version-show-footer">
        <Button @click="cancelHandler" style="margin-right:8px">取消</Button>
        <Button type="primary" @click="okHandler">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { getTemplateList, getTemplateListVersion, delTemplateByVersion, delTemplate } from 'http/api/mark';
import { routePathData } from 'assets/scripts/common'
export default {
  data () {
    return {
      pagination: {
        total: 10,
        current: 1,
        pageSize: 10
      },
      columns: [
        {
          title: '序号',
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: 'templateName',
          key: 'name',
          width: 300
        },
        {
          title: 'templateId',
          key: 'id'
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center',
          slot: 'action'
        }
      ],
      templateData: [],
      versionShow: false,
      actionName: '',
      actionId: '',
      version: '',
      versionObj: {} // 根据记录版本号信息
    };
  },

  methods: {
    cancelHandler () {
      this.versionShow = false;
      this.actionName = '';
      this.actionId = '';
      this.version = '';
    },

    async okHandler () {
      switch (this.actionName) {
        case '删除':
          if (this.version) {
            // 判断是不是只有一条数据，如果当前版本删除，模板删除
            let len = this.versionObj[this.actionId].length;
            if (len === 1) {
              this.toDel('该版本删除后将同步删除模板，数据删除后不可恢复，确认删除吗？')
            } else {
              await delTemplateByVersion({ id: this.actionId, version: this.version });
              // 删除记录数据
              delete this.versionObj[this.actionId]
              this.$delete(this.versionObj, this.actionId);
              this.$Message.success(`版本v${this.version}删除成功`);
              this.cancelHandler();
            }
          } else {
            this.toDel()
          }

          break;
        case '编辑':
          // 用于判断不是从预览页面返回的标识
          sessionStorage.removeItem('fromPreview')
          this.$router.push({ path: `${routePathData.markVisual}?id=${this.actionId}&version=${this.version}` });
          break;
      }
    },

    addTemplate () {
      this.$router.push({ path: routePathData.markVisual });
    },

    // 编辑1/删除0
    async toEditOrDel (row, type) {
      // 点击时候获取数据
      this.versionShow = true;
      this.actionName = type === 1 ? '编辑' : '删除';
      this.actionId = row.id;

      let versionArr = this.versionObj[this.actionId];
      if (versionArr) {
        let len = versionArr.length;
        this.version = versionArr[len - 1].version;
      } else {
        let res = await getTemplateListVersion({ id: row.id, page: 1, size: 1000 });

        if (res && res.items.length) {
          this.$set(this.versionObj, this.actionId, res.items);
          this.version = res.items[res.items.length - 1].version;
        }
      }
    },

    // 没有版本号后直接删除模板
    async toDel (tip) {
      this.$Modal.confirm({
        title: '删除提示',
        content: tip ? `<p>${tip}</p>` : `<p>您未选择版本号，将删除该模板且数据删除后不可恢复，确认删除吗？</p>`,
        onOk: async () => {
          await delTemplate(this.actionId);
          this.pagination.current = 1;
          this.getTemplateList();
          this.$Message.success('模板删除成功')
          this.cancelHandler();
        }
      });
    },

    changePageNum (pageNum) {
      this.pagination.current = pageNum;
      this.getTemplateList();
    },
    changePageSize (size) {
      this.pagination.pageSize = size;
      this.changePageNum(1);
    },
    getTemplateList () {
      let param = {
        page: this.pagination.current,
        size: this.pagination.pageSize
      };
      getTemplateList(param).then(res => {
        if (res) {
          this.templateData = res.items;
          this.pagination.total = res.total;
        }
      })
        .catch(err => {
          this.$Message.error(err);
        })
    }
  },

  mounted () {
    this.versionObj = {}
    this.getTemplateList();
  }
};
</script>

<style rel="stylesheet/less" lang="less" scoped>
.template-list {
  padding: 20px;
  .template-content {
    margin: 20px 0;
  }
}
</style>

<style lang="less">
.version-show-model {
  .ivu-modal-body {
    padding-bottom: 72px;
  }
  .version-show-item {
    margin-top: 28px;

    .version-bold {
      font-weight: bold;
      color: #3b98f2;
      font-size: 12px;
      &.del {
        color: #d15b47;
      }
    }
  }
  .version-show-footer {
    float: right;
    margin-top: 20px;
  }
  .ivu-select {
    width: 220px;
  }
}
</style>
